package com.demo;

import com.common.HttpRequest;
import com.common.publicMethod;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.param.LandParam.LandDuplicationParam;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MultiThreadedCityProcessor {

    @Autowired
    private publicMethod publicMethod;


 //   @Scheduled(cron = "0/8 * * * * ? ")
/*    public void test() {
        log.error("one开始:{}", System.currentTimeMillis());
        String sqlCookie = publicMethod.getSqlCookie();
        List<String> cityList = publicMethod.getAllCity(sqlCookie);


        // 定义线程池大小，例如使用系统的核心数
        int threadPoolSize = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        // 用来存储所有Future对象，以便后续可以获取每个任务的结果
        List<Future<Object>> futures = new ArrayList<>(cityList.size());

        // CountDownLatch用来等待所有任务完成
        CountDownLatch latch = new CountDownLatch(cityList.size());

        for (String city : cityList) {
            // 提交任务给线程池，并获取Future对象
            Future<Object> future = executorService.submit(() -> {
                try {
                    // 调用A接口，假设有一个方法叫callAInterface，返回Object类型的结果
                    List<LandDuplicationParam> result = callAInterface(city);
                    return result;
                } catch (Exception e) {
                    // 处理异常
                    e.printStackTrace();
                    return null;
                } finally {
                    // 计数减一，表示一个任务完成
                    latch.countDown();
                }
            });
            futures.add(future);
        }

        try {
            // 等待所有任务完成
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
            executorService.shutdownNow(); // 中断所有任务
            throw new RuntimeException(e);
        }

        // 收集所有结果
        List<Object> obj = new ArrayList<>();
        for (Future<Object> future : futures) {
            try {
                // 获取每个任务的结果，如果任务还没有完成，这里会阻塞
                obj.add(future.get());
            } catch (InterruptedException | ExecutionException e) {
                // 处理异常情况
                e.printStackTrace();
            }
        }
        log.error("one结束:{}", System.currentTimeMillis());
        // 关闭线程池
        executorService.shutdown();

        // 打印或处理结果集合obj...
    }*/

  /*  private List<LandDuplicationParam> callAInterface(String city) throws JsonProcessingException {

        List<Integer> columnListThree = new ArrayList<>();
        columnListThree.add(3);
        columnListThree.add(2);
        columnListThree.add(98);
        List<LandDuplicationParam> needList = new ArrayList<>();
        List<LandDuplicationParam> landList = new ArrayList<>();
        for (Integer integer : columnListThree) {

            JSONObject param1 = new JSONObject();
            JSONObject param3 = new JSONObject();
            JSONObject param4 = new JSONObject();
            param4.put("@column", "count(1):num");
            param3.put("state", 1);
            param3.put("CityCaption", city);
            param3.put("id@", "/Land_Shu/Buildingid");
            param4.put("State", 1);


            param4.put("Columnid", integer);
            param1.put("join", "&/Internal_Land_BaseInfo_Main/id@");
            param1.put("Land_Shu", param4); //左表
            param1.put("Internal_Land_BaseInfo_Main", param3); //右表

            net.sf.json.JSONObject param2 = new net.sf.json.JSONObject();

            param2.put("[]", param1);

            String sr = HttpRequest.sendPostAPI("get", param2.toString(), publicMethod.getSqlCookie());
            net.sf.json.JSONObject sqlData = net.sf.json.JSONObject.fromObject(sr);
            int newCount = 0;
            if (sqlData.getBoolean("ok") == true && sqlData.containsKey("[]")) {
                for (Object s1 : sqlData.getJSONArray("[]")) {
                    net.sf.json.JSONObject details = ((JSONObject) s1).getJSONObject("Land_Shu");
                    newCount = details.getInt("num");
                }
            }

            param3.put("@column", "id");
            param3.put("@order", "id-");
            param4.put("@column", "Columnid,Value,Buildingid");
            param1.put("Land_Shu", param4); //左表
            param1.put("Internal_Land_BaseInfo_Main", param3); //右表
            int cycleNum = 0;
            if (newCount > 50000) {
                cycleNum = newCount / 50000 + 1;
            }
            for (int page = 0; page <= cycleNum; page++) {

                param1.put("page", page);
                param1.put("count", 50000);
                param2.put("[]", param1);
                long start = System.currentTimeMillis();
                String ssr = HttpRequest.sendPostAPI("get", param2.toString(),  publicMethod.getSqlCookie());
                long end = System.currentTimeMillis();
                long differ = end - start;
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(ssr);
                JsonNode jsonNode = rootNode.get("[]");
                if (jsonNode != null) {

                    for (JsonNode node : jsonNode) {

                        JsonNode detailsMain = node.get("Internal_Land_BaseInfo_Main");
                        JsonNode detailsShu = node.get("Land_Shu");

                        LandDuplicationParam duplication = new LandDuplicationParam();
                        if (detailsMain.has("id")) {
                            JsonNode longValueNode = detailsMain.get("id");
                            if (longValueNode != null) {
                                // 安全地获取long值
                                long id = longValueNode.asLong();
                                duplication.setId(id);
                            }
                            JsonNode cityValue = detailsMain.get("CityCaption");
                            if (cityValue != null) {
                                // 安全地获取String的值
                                String citys = cityValue.asText();
                                duplication.setCityCaption(citys);
                            }

                            JsonNode Columnid = detailsShu.get("Columnid");
                            if (Columnid != null) {
                                // 安全地获取String的值
                                String columnid = Columnid.asText();
                                duplication.setColumnId(columnid);
                            }

                            JsonNode Value = detailsShu.get("Value");
                            if (Value != null) {
                                // 安全地获取String的值
                                String value = Value.asText();
                                duplication.setValue(value);
                            }
                            landList.add(duplication);
                        }
                    }
                }
            }
        }
        //将id相同 ,column不同的数据 .分组到一起
        Map<Long, List<LandDuplicationParam>> GroupsById = landList.stream()
                .collect(Collectors.groupingBy(LandDuplicationParam::getId));

        List<LandDuplicationParam> allList = new ArrayList<>();
        for (List<LandDuplicationParam> value : GroupsById.values()) {
            LandDuplicationParam allLandParam = new LandDuplicationParam();
            LandDuplicationParam param = value.get(0);
            allLandParam.setId(param.getId());
            allLandParam.setCityCaption(param.getCityCaption());
            allLandParam.setLandCaption(param.getLandCaption());
            for (int i = 0; i < value.size(); i++) {
                LandDuplicationParam columnValue = value.get(i);
                //区域
                if (StringUtils.equals("3", columnValue.getColumnId())) {
                    allLandParam.setRegion(columnValue.getValue());
                }
                //信息来源
                if (StringUtils.equals("2", columnValue.getColumnId())) {
                    allLandParam.setSource(columnValue.getValue());
                }

                //宗地编号
                if (StringUtils.equals("98", columnValue.getColumnId())) {
                    allLandParam.setLandNum(columnValue.getValue());
                }
            }
            allList.add(allLandParam);
        }

        // 根据条件找出重复的土地
        Map<List<Object>, List<LandDuplicationParam>> group = allList.stream().filter(
                s -> !StringUtils.isEmpty(s.getLandNum()))
                .collect(Collectors.groupingBy(
                        s -> Arrays.asList(s.getLandNum(), s.getRegion())
                ));
        // 过滤出含有超过一个土地的组，并检查信息来源是否不同但其他属性相同
        List<List<LandDuplicationParam>> duplicates = group.entrySet().stream()
                .filter(entry -> entry.getValue().size() > 1)
                .map(entry -> {
                    List<LandDuplicationParam> dupList = entry.getValue();
                    return dupList.stream()
                            .filter(s -> dupList.stream()
                                    .anyMatch(other -> {
                                        // 检查两个Source是否都不为null且不相等，或者其中一个为null而另一个不为null
                                        return (s.getSource() != null && other.getSource() != null && !s.getSource().equals(other.getSource()))
                                                || (s.getSource() == null && other.getSource() != null)
                                                || (s.getSource() != null && other.getSource() == null);
                                    }))
                            .collect(Collectors.toList());
                })
                .filter(list -> !list.isEmpty()) // 过滤出非空的重复列表
                .collect(Collectors.toList());
        for (List<LandDuplicationParam> duplicate : duplicates) {
            if (duplicate.size() > 1) {

                LandDuplicationParam param = new LandDuplicationParam();
                param.setCount(duplicate.size());
                param.setCityCaption(city);
                param.setLandNum(duplicate.get(0).getLandNum());
                List<Long> idList = new ArrayList<>();
                String ids = "";
                for (int i = 0; i < duplicate.size(); i++) {
                    if (StringUtils.isEmpty(duplicate.get(i).getRegion()) || StringUtils.isEmpty(duplicate.get(i).getLandNum())) {
                        continue;
                    }
                    idList.add(duplicate.get(i).getId());
                    ids = ids + String.valueOf(duplicate.get(i).getId()) + ";";
                }
                if (!CollectionUtils.isEmpty(idList)) {
                    //根据idList  获取landCaption
                    //     String landCaption = this.getLandCaptionById(idList, sqlCookie);
                    //     param.setLandCaption(landCaption);
                    param.setIdList(ids);
                    param.setCheckDate(publicMethod.getNowDate());
                    //    param.setRepeatGoal(replaceGoalNum++);
                    param.setDuplicationReason("来源不一致宗地编号重复");
                    needList.add(param);
                }
            }
        }
        return needList;
    }*/
}